package com.littleken.utils;

import com.littleken.config.sqlConfig;

import java.sql.*;

public class SqlUtil {
    /**
     * 打开数据库连接
     *
     * @return
     */
    public static Connection open() {

        Connection conn = null;
        try {
            Class.forName(sqlConfig.MYSQL_DRIVER);
            conn = DriverManager.getConnection(sqlConfig.MYSQL_URL, sqlConfig.MYSQL_USERNAME, sqlConfig.MYSQL_USERPASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭数据库
     *
     * @param con   数据库连接
     * @param pstmt 数据库语句
     * @param rs    数据集
     */
    public static void close(Connection con, PreparedStatement pstmt, ResultSet rs) {

        try {
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 数据查询
     *
     * @return
     */
    public static ResultSet getResultSet(String sql) {
        Connection con = open();
        Statement stmt = null;
        ResultSet rs = null;
        try {
            stmt = con.createStatement();
            rs = stmt.executeQuery(sql);
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }


}
